package com.example.game

import kotlin.random.Random

class GameModel {

    private val _cards = mutableListOf<Card>()
    val cards: List<Card> get() = _cards

    private var _currentScore = 0
    val currentScore: Int get() = _currentScore

    private var _flippedCards = mutableListOf<Int>() // 存储已翻转卡片的索引
    private var _matchedPairs = 0
    val matchedPairs: Int get() = _matchedPairs

    // 卡片图片资源ID数组（8种不同的图片，每种两张）
    private val cardImages = arrayOf(
        R.drawable.card_1,
        R.drawable.card_2,
        R.drawable.card_3,
        R.drawable.card_4,
        R.drawable.card_5,
        R.drawable.card_6,
        R.drawable.card_7,
        R.drawable.card_8
    )

    // 背面图片资源ID
    val cardBackResId = R.drawable.card_back

    init {
        initializeGame()
    }

    // 初始化游戏
    private fun initializeGame() {
        _cards.clear()
        _flippedCards.clear()
        _matchedPairs = 0
        _currentScore = 0

        // 创建16张卡片：8对相同图片
        val cardList = mutableListOf<Card>()
        for (i in 0 until 8) {
            // 每种图片创建两张卡片
            cardList.add(Card(i * 2, cardImages[i]))
            cardList.add(Card(i * 2 + 1, cardImages[i]))
        }

        // 随机打乱卡片顺序
        _cards.addAll(cardList.shuffled(Random(System.currentTimeMillis())))
    }

    // 翻转卡片
    fun flipCard(cardIndex: Int): Boolean {
        if (cardIndex < 0 || cardIndex >= _cards.size) return false
        if (_cards[cardIndex].isMatched || _cards[cardIndex].isFlipped) return false

        _cards[cardIndex].flip()
        _flippedCards.add(cardIndex)

        // 如果翻转了两张卡片，检查是否匹配
        if (_flippedCards.size == 2) {
            val card1 = _cards[_flippedCards[0]]
            val card2 = _cards[_flippedCards[1]]

            if (card1.imageResId == card2.imageResId) {
                // 匹配成功
                card1.setMatched()
                card2.setMatched()
                _matchedPairs++
                _currentScore += 10 // 每匹配一对加10分
                _flippedCards.clear()
                return true
            }
        }

        return false
    }

    // 检查是否需要翻回卡片（当翻转了两张不匹配的卡片时调用）
    fun checkAndFlipBack(): List<Int> {
        if (_flippedCards.size == 2) {
            val indicesToFlipBack = _flippedCards.toList()
            // 翻转回背面
            _cards[_flippedCards[0]].flip()
            _cards[_flippedCards[1]].flip()
            _flippedCards.clear()
            return indicesToFlipBack
        }
        return emptyList()
    }

    // 检查游戏是否结束
    fun isGameFinished(): Boolean {
        return _matchedPairs == 8 // 8对卡片全部匹配
    }

    // 重置游戏
    fun resetGame() {
        initializeGame()
    }

    // 获取当前翻转的卡片索引（用于延迟翻回）
    fun getFlippedCardIndices(): List<Int> {
        return _flippedCards.toList()
    }
}


